from sqlalchemy import Column, Integer, String, Date, JSON, Enum
from database import Base
from sqlalchemy.orm import relationship
from sqlalchemy import ForeignKey

class Prescription(Base):
    __tablename__ = "prescription"

    ID = Column(Integer, primary_key=True, index=True, autoincrement=True)
    doctor_ID = Column(Integer, ForeignKey("doctor.ID"))
    patient_ID = Column(Integer, ForeignKey("patient.ID"))
    pre_date = Column(Date)
    medicines=Column(JSON)
    is_done = Column(Enum("Y","N"))

    # 定义关系
    doctor = relationship("Doctor", back_populates="prescriptions")
    patient = relationship("Patient", back_populates="prescriptions")

    def to_dict(self):
        return {
            "ID": self.ID,
            "doctor_ID": self.doctor_ID,
            "patient_ID": self.patient_ID,
            "pre_date": self.pre_date,
            "medicines": self.medicines,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "Prescription":
        valid_keys = set(cls.__table__.columns.keys())
        return cls(**{k: v for k, v in data.items() if k in valid_keys})